package cn.utils;

import cn.utils.imgs.HttpUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class SMSUtils {
    private static ObjectMapper om = new ObjectMapper();
    public static Map<String, Object> sendVerify(String phone) {

        // 存放结果
        Map<String, Object> res = new HashMap<>();

        String host = BaseUtils.getProString("smsHost");
        String path = BaseUtils.getProString("smsPath");
        String method = "POST";
        String appcode = BaseUtils.getProString("smsAppCode");
        String verifyCode = BaseUtils.getRandomNum(6);
        Map<String, String> headers = new HashMap<String, String>();

        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();

        bodys.put("callbackUrl", "http://test.dev.esandcloud.com");
        bodys.put("channel", "0");
        bodys.put("mobile", "+86" + phone);
        bodys.put("templateID", BaseUtils.getProString("smsVerifyID"));
        bodys.put("templateParamSet", verifyCode);


        try {

            HttpResponse response = HttpUtil.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            String result = EntityUtils.toString(response.getEntity());

            Map<String, Object> sms = om.readValue(result, new TypeReference<Map<String, Object>>() {});
            LoggerUtils.info("发送验证码" + sms);
            if ("0000".equals(sms.get("code"))) {
                res.put("msg", true);
                res.put("code", verifyCode);
            } else {
                res.put("msg", false);
                res.put("error", sms.get("msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.put("msg", false);
        }

        return res;
    }
}
